<style>
    .ivu-btn-primary {
        color: #fff;
        background-color: #006ec7 !important;
        border-color: #006ec7 !important;
    }

    .ivu-checkbox-checked .ivu-checkbox-inner {
        border-color: #006ec7 !important;
        background-color: #006ec7 !important;
    }

    .ivu-btn-info {
        color: #fff;
        background-color: #006ec7 !important;
        border-color: #006ec7 !important;
    }
    .ivu-page-item-active {
        background-color: #ffffff !important;
        border-color: #006ec7 !important;
    }
    .ivu-page-item-active a {
        color: inherit !important;
    }

    .ivu-tabs-nav-container {
        margin-bottom: -1px;
        line-height: 1.5;
        font-size: 18px;
        box-sizing: border-box;
        white-space: nowrap;
        overflow: hidden;
        position: relative;
        zoom: 1;
    }
    .ivu-tabs-nav .ivu-tabs-tab-active {
        color: #006ec7;
    }
    .ivu-tabs-nav .ivu-tabs-tab {
        display: inline-block;
        height: 100%;
        padding: 20px 16px;
        margin-right: 16px;
        box-sizing: border-box;
        cursor: pointer;
        text-decoration: none;
        position: relative;
        transition: color 0.3s ease-in-out;
    }
    .ivu-icon-ios-arrow-down:before {
        content: url('/static/images/menu/more.png');
    }
    .ivu-menu-opened > * > .ivu-menu-submenu-title-icon {
        transform: rotate(180deg);
    }
</style>
<template>
    <div class="" style="height: 100%;" @click="hideTips">
        <div id="yolo-header" :style="{ backgroundColor: '#41B24E', backgroundsize: 'contain', height: '70px', width: '100%' }">
            <div class="head-contain">
                <div class="head-menu">
                    <div :class="isCollapsed ? 'tool menu' : 'tool menuv'" @click="collapsedSider">
                        <img src="/static/images/newfleet/menu.png" />菜单
                    </div>
                    <div class="tool full" @click="doAllScreen">全屏</div>
                </div>
                <div class="logo">
                    <div class="icon-logo" :style="{backgroundImage:'url(' +(sysConfig.home_logo !== undefined ? sysConfig.home_logo : '/static/images/index/yolo_logo.png') +')'}"></div>
                    <div class="head-title">
                        <div class="title-zh">运营管理平台</div>
                    </div>
                </div>
                <div class="top-menu-tools">
                    <div style="position: relative;" @click.stop="showUserCerter">
                        <div class="icon-head">
                            <img :src="user.userPath ? user.userPath : '/static/images/ser_admini_appli_head_default@3x.png'" />
                            <div class="head-name">{{ user.userNickName }}</div>
                            <div class="option"></div>
                        </div>
                        <div class="fixUserDiv" v-show="fixUserDivModel">
                            <div class="user-center" id="userCenterInfo" @click="goto('/user/userCenterInfo')">
                                <img class="user-center-icon" src="/static/images/menu/navigation_usercenter_nor.png" />
                                <span>用户中心</span>
                            </div>
                            <div class="user-center" @click="modal = true">
                                <img class="user-center-icon" src="/static/images/menu/navigation_signout_nor.png" />
                                <span>退出</span>
                            </div>
                        </div>
                    </div>
                    <div class="tools-contain"></div>
                </div>
            </div>
        </div>

        <div style="height: calc(100% - 70px);">
            <div class="main-container">
                <Layout style="width: 100%;">
                    <Sider ref="side1" hide-trigger collapsible :collapsed-width="100" width="250" v-model="isCollapsed">
                        <div v-show="!isCollapsed" class="container-left" @mouseleave="mouseleave">
                            <div class="logo">
                                <div class="logo-div">
                                    <img :src="user.logoPath !== null && user.logoPath !== undefined && user.logoPath !== '' ? user.logoPath: '/static/images/navigation_jigou_defaulthead.png'"/>
                                </div>
                                <div class="orgName">
                                    {{ user.userNickName }}
                                </div>
                            </div>
                            <div class="menulist">
                                <Menu theme="light" width="auto" accordion @on-select="clickmenue">
                                    <MenuItem name="-1">
                                        <router-link to="/">
                                            <div :class="{ home: menuindex === '-1', 'home-unselected': menuindex !== '-1' }">
                                                <div :class="{ 'select-icon': menuindex === '-1', 'unselect-icon': menuindex !== '-1' }"
                                                     :style="{ mask: 'url(/static/images/menu/home.svg)',  webkitMask: 'url(/static/images/menu/home.svg)' }" ></div>
                                                <span> 首页</span>
                                            </div>
                                        </router-link>
                                    </MenuItem>
                                    <Submenu :name="index" v-for="(menu, index) in sideBarLinks" v-if="menu.list != null" :key="index">
                                        <template slot="title">
                                            <div style="display: inline-block;">
                                                <div style="display: flex;">
                                                    <span :class="{ 'select-icon': menuindex === index + '', 'unselect-icon': menuindex !== index + ''}"
                                                          :style="{ mask: 'url(' + menu.icon + ')', webkitMask: 'url(' + menu.icon + ')'}"></span>
                                                    <span :class="{ 'active-name menu-title': menuindex === index + '', 'unactive-name menu-title': menuindex !== index + ''}">
                                                        {{ menu.name }}
                                                    </span>
                                                </div>
                                            </div>
                                        </template>
                                        <router-link :to="subMenu.url" v-for="(subMenu, key) in menu.list" :key="key">
                                            <MenuItem :name="index + '-' + key">
                                                <div style="margin-left: 12px;">{{ subMenu.name }}</div>
                                            </MenuItem>
                                        </router-link>
                                    </Submenu>
                                </Menu>
                            </div>
                        </div>
                        <div class="container-left" style="width: 120px;" @mouseenter="mouseenter" v-show="isCollapsed">
                            <div class="logo" style="margin-bottom: 30px;">
                                <div class="logo-div" style="width: 60px;height: 60px;">
                                    <img src="user.logoPath !== null && user.logoPath !== undefined && user.logoPath !== '' ? user.logoPath : '/static/images/navigation_jigou_defaulthead.png'"
                                         style="width: 60px;height: 60px;"/>
                                </div>
                            </div>
                            <div class="menulist">
                                <MenuItem name="-1">
                                    <router-link to="/">
                                        <div :class="{ 'select-icon': menuindex === '-1', 'unselect-icon': menuindex !== '-1' }"
                                             :style="{mask: 'url(/static/images/menu/home.svg)',webkitMask: 'url(/static/images/menu/home.svg)',marginBottom: '10px'}"
                                        ></div>
                                    </router-link>
                                </MenuItem>
                                <Menu theme="light" width="auto" accordion @on-select="clickmenue">
                                    <MenuItem
                                            :name="index"
                                            v-for="(menu, index) in sideBarLinks"
                                            v-if="menu.list != null"
                                            :key="index"
                                            :class="{'active-name select-bg': menuindex === index + '','unactive-name unselect-bg': menuindex !== index + ''}">
                                        <div :class="{ 'select-icon': menuindex === index + '', 'unselect-icon': menuindex !== index + '' }"
                                             :style="{mask: 'url(' + menu.icon + ')',webkitMask: 'url(' + menu.icon + ')',marginLeft: '16px'}"></div>
                                    </MenuItem>
                                </Menu>
                            </div>
                        </div>
                    </Sider>
                    <Layout>
                        <Content>
                            <div class="container-right" id="mainContainer">
                                <div>
                                    <div v-if="$route.path !== '/'" style="background-color: #ffffff;padding: 10px 30px;">
                                        <Breadcrumb id="yolo-breadcrumb" :style="{ height: '30px', lineHeight: '30px' }">
                                            <BreadcrumbItem v-if="$route.path !== '/'">{{ $route.meta.title }}</BreadcrumbItem>

                                            <template v-for="(navi, index) in $route.meta.navigation">
                                                <template v-if="navi.path !== null && navi.path !== ''">
                                                    <BreadcrumbItem>{{ navi.name }}</BreadcrumbItem>
                                                </template>

                                                <template v-else>
                                                    <BreadcrumbItem>{{ navi.name }}</BreadcrumbItem>
                                                </template>
                                            </template>
                                        </Breadcrumb>
                                    </div>
                                    <div v-if="$route.path == '/'" style="padding:  0 30px;margin-top: 20px;">
                                        <!--<common-main></common-main>-->
                                    </div>
                                    <div style="padding:  0 30px;">
                                        <router-view></router-view>
                                        <div id="paddingbottomid" style="padding-bottom: 100px;"></div>
                                    </div>

                                    <div class="top" v-show="showBackTop" @click="goBackTop">
                                        <Icon type="chevron-up">返回</Icon>
                                    </div>
                                </div>
                            </div>
                        </Content>
                    </Layout>
                </Layout>
            </div>
        </div>

        <Modal v-model="modal" width="360">
            <p slot="header" style="color:#f60;text-align:center">
                <Icon type="information-circled"></Icon>
                <span>温馨提示</span>
            </p>
            <div style="text-align:center">
                <p>您确认要退出?退出后将无法操作哦!</p>
            </div>
            <div slot="footer">
                <Button type="warning" size="large" long :loading="modalLoading" @click="signOut">确认退出</Button>
            </div>
        </Modal>
        <!--<PersonInfo ref="personInfo"></PersonInfo>-->
        <!--<UserRestPwd ref="modPassword"
                     v-on:eventChild="respModPassword"></UserRestPwd>
        <ModUserPhone ref="modUserPhone"
                      v-on:eventChild="respModUserPhone"></ModUserPhone>-->
    </div>
</template>

<script>
    import screenfull from 'screenfull';

    export default {
        name: 'index',
        data: function() {
            return {
                sysConfig: {},
                sideBarLinks: [],
                eventlist: [],
                list: [],
                msglist: [],
                totalNum: 0,
                msgNum: 0,
                num: 0,
                logoPath: '',
                user: {},
                fixUserDivModel: false,
                msgModel: false,
                alarModel: false,
                org: {
                    orgPath: '',
                    orgName: ''
                },
                modalLoading: false,
                modal: false,
                personModal: {
                    win: false,
                    cancleButton: true
                },
                showBackTop: false,
                addressCarInfoMap: new Map(),
                selectType: 8,
                userInfo: {},
                isCollapsed: false,
                hideflag: false,
                menuindex: '-1'
            };
        },
        methods: {
            hideTips() {
                this.msgModel = false;
                this.fixUserDivModel = false;
            },
            clickmenue(name) {
                if (name !== '-1') {
                    let arr = name.split('-');
                    this.menuindex = arr[0];
                    console.log(this.menuindex);
                } else {
                    this.menuindex = '-1';
                }
                window.sessionStorage.setItem('active-name', name);
            },
            mouseenter() {
                this.isCollapsed = false;
            },
            mouseleave() {
                if (!this.hideflag) {
                    this.isCollapsed = false;
                } else {
                    this.isCollapsed = true;
                }
            },
            collapsedSider() {
                this.$refs.side1.toggleCollapse();
                this.hideflag = this.isCollapsed;
            },
            getSysConfig() {
                this.request('getSysConfig', {}, false)
                    .then(res => {
                        this.sysConfig = res;
                        // 设置地图key
                        if (this.sysConfig && this.sysConfig.map_key) {
                            window.DMap.key = this.sysConfig.map_key;
                        }
                        if (this.sysConfig && this.sysConfig.map_address) {
                            window.DMap.addressKey = this.sysConfig.map_address;
                        }
                        window.sessionStorage.setItem('sysConfig', JSON.stringify(res));
                    })
                    .catch(error => {
                        console.log(error);
                    });
            },
            doAllScreen() {
                screenfull.toggle();
            },
            goBackTop() {
                let mainContainer = document.getElementById('mainContainer');
                mainContainer.scrollTop = 0;
            },
            handleScroll(event) {
                if (event.srcElement.scrollTop > event.srcElement.scrollHeight / 4) {
                    this.showBackTop = true;
                } else {
                    this.showBackTop = false;
                }
            },
            getUserMenu() {
                let uid = this.getLoginInfo().userId;
                let params = { uid: uid };
                this.request('getUserMenu', params, false)
                    .then(res => {
                        console.log(JSON.stringify(res))
                        this.sideBarLinks = res;
                    })
                    .catch(error => {
                        console.log(error);
                    });
            },
            signOut() {
                this.modalLoading = true;
                setTimeout(() => {
                    this.modalLoading = false;
                    this.modal = false;
                    //清除临时的本地存储
                    window.sessionStorage.removeItem('loginInfo');
                    window.sessionStorage.removeItem('loginToken');
                    this.$Message.success('退出成功');
                    this.$router.push({ path: '/login' });
                }, 1000);
            },
            goto(url, query) {
                this.$router.push({ path: url, query: query });
            },
            showUserCerter() {
                this.fixUserDivModel = !this.fixUserDivModel;
            },
            leave() {
                this.fixUserDivModel = false;
            },
            goSecurity() {
                this.$router.push({ path: '/security/car_list' });
            },
            showMsgCerter() {
                this.msgModel = !this.msgModel;
            },
            select(type) {
                this.list = [];
                this.selectType = type;
                if (this.selectType === 8) {
                    this.$set(this, 'list', this.eventlist);
                } else {
                    console.log(this.msglist);
                    this.$set(this, 'list', this.msglist);
                }
            },
            initDics() {
                this.request('dics')
                    .then(res => {
                        let carNatureArrs = res.car_nature;
                        let carOutputArrs = res.car_output;
                        let carSeatArrs = res.car_seat;
                        let carEmissionArrs = res.car_emission;
                        let energyArrs = res.energy;
                        let gasNoArrs = res.gas_no;
                        let carBodyArrs = res.car_body;
                        window.sessionStorage.setItem('carNatureArrs', JSON.stringify(carNatureArrs));
                        window.sessionStorage.setItem('carOutputArrs', JSON.stringify(carOutputArrs));
                        window.sessionStorage.setItem('carSeatArrs', JSON.stringify(carSeatArrs));
                        window.sessionStorage.setItem('carEmissionArrs', JSON.stringify(carEmissionArrs));
                        window.sessionStorage.setItem('energyArrs', JSON.stringify(energyArrs));
                        window.sessionStorage.setItem('gasNoArrs', JSON.stringify(gasNoArrs));
                        window.sessionStorage.setItem('carBodyArrs', JSON.stringify(carBodyArrs));
                    })
                    .catch(error => {
                        console.log(error);
                    });
            },
            changeUserPhone() {
                this.leave();
                this.$refs.modUserPhone.open();
            },
            modPassword() {
                this.leave();
                this.$refs.modPassword.open();
            },
            respModPassword() {
                this.$refs.modPassword.close();
            },
            respModUserPhone() {
                this.$refs.modUserPhone.close();
            },
            msgList() {
                this.eventlist = [];
                this.msglist = [];
                this.list = [];
                this.request('carOrgArrsIndexEvents')
                    .then(res => {
                        let num = 0;
                        let totalNum = 0;
                        for (let i = 0; i < res.list.length; i++) {
                            num++;
                            let item = res.list[i];
                            if (item.type === 1) {
                                this.pasertAddress(item);
                            }
                            this.eventlist.push(item);
                        }
                        let msgNum = 0;
                        this.msglist = res.msglist;
                        if (this.msglist && this.msglist.length > 0) {
                            msgNum = this.msglist.length;
                        }
                        totalNum = num + msgNum;
                        this.totalNum = totalNum;
                        this.msgNum = msgNum;
                        this.num = num;
                        this.userView();
                    })
                    .catch(error => {
                        this.isMask = false;
                        console.log(error);
                    });
            },
            getAlarmName(alarmId) {
                let name = '';
                switch (parseInt(alarmId)) {
                    case 0x0001:
                        name = '车辆启动了';
                        break;
                    case 0x0002:
                        name = '车辆熄火了';
                        break;
                    case 0x0107:
                        name = '超速行驶';
                        break;
                    case 0x0108:
                        name = '疲劳驾驶';
                        break;
                    case 0x0111:
                        name = '急加速';
                        break;
                    case 0x0112:
                        name = '急减速';
                        break;
                    case 0x0113:
                        name = '急转弯';
                        break;
                    case 0x0106:
                        name = '怠速时间过长';
                        break;
                    case 0x0105:
                        name = '电瓶电压低';
                        break;
                    case 0x9999:
                        name = '产生了故障';
                        break;
                    case 0x9998:
                        name = '驶入禁入围栏';
                        break;
                    case 0x9997:
                        name = '驶出禁出围栏';
                        break;
                    case 0x0103:
                        name = '终端被拔出';
                        break;
                    case 0x0104:
                        name = '终端已接入';
                        break;
                    default:
                        name = '';
                        break;
                }
                return name;
            },
            getAlarmDesTitle(alarmId) {
                let name = '';
                switch (parseInt(alarmId)) {
                    case 0x0001:
                    case 0x0002:
                    case 0x0111:
                    case 0x0112:
                    case 0x0113:
                    case 0x0106:
                    case 0x0103:
                    case 0x0104:
                        name = '当时位置：';
                        break;
                    case 0x0107:
                    case 0x0108:
                        name = '当时车速：';
                        break;
                    case 0x0105:
                        name = '当时电压：';
                        break;
                    case 0x9999:
                        name = '故障码：';
                        break;
                    case 0x9998:
                    case 0x9997:
                        name = '围栏名称：';
                        break;
                    default:
                        name = '';
                        break;
                }
                return name;
            },
            getAlarmDesValue(alarm) {
                return alarm.content;
            },
            getFualtStr(faultList) {
                let str = '';
                if (faultList && faultList.length > 0) {
                    let len = faultList.length;
                    let i = 0;
                    for (i in faultList) {
                        if (parseInt(i) === len - 1) {
                            str += faultList[i];
                        } else {
                            str += faultList[i] + '、';
                        }
                    }
                }
                return str;
            },
            pasertAddress(alarm) {
                let endgdGsp = window.Util.wgs84togcj02(alarm.longitude, alarm.latitude);
                let location = endgdGsp[0] + ',' + endgdGsp[1];
                axios
                    .get(
                        'https://restapi.amap.com/v3/geocode/regeo?key=' +
                        window.DMap.addressKey +
                        '&location=' +
                        location +
                        '&poitype=&radius=1000&extensions=base&batch=false&roadlevel=0'
                    )
                    .then(res => {
                        this.$set(alarm, 'content', res.data.regeocode.formatted_address);
                        console.log(res.data.regeocode.formatted_address);
                    })
                    .catch(error => {
                        console.log(error);
                    });
            },
            clear() {
                let params = {};
                params.type = this.selectType;
                this.request('clearMsg', params)
                    .then(() => {
                        this.$Message.info('清空成功');
                        this.msgList();
                        this.select(this.selectType);
                    })
                    .catch(error => {
                        this.isMask = false;
                        console.log(error);
                    });
            },
            event(carId) {
                this.msgModel = false;
                this.$refs.carTotallistView.open(carId);
            },
            goNewsDetail(keyId, isBulletin) {
                this.msgModel = false;
                this.$router.push({ name: '服务/通知详情2', query: { keyId: keyId, isBulletin: isBulletin } });
            },
            userView() {
                this.request('userView')
                    .then(res => {
                        this.userInfo = res;
                        if (this.userInfo.roleName === '管理员(系统)') {
                            this.alarModel = true;
                            this.select(8);
                        } else {
                            this.select(9);
                        }
                    })
                    .catch(error => {
                        console.log(error);
                    });
            },
            findBaseUrl() {
                this.request('findBaseUrl', {})
                    .then(res => {
                        window.sessionStorage.setItem('baseUrl', res.shareUrl);
                    })
                    .catch(e => {
                        console.log(e);
                    });
            }
        },
        filters: {
            fmtTime(val) {
                if (val === '' || val === null || val === undefined) {
                    return '';
                }
                return window.Util.filterTime(val, 'ymd-hm');
            },
            fmtTitle(val) {
                let len = 16;
                if (val !== undefined && val !== null && val !== '' && val.length > len) {
                    return val.substring(0, len) + '...';
                }
                return val;
            }
        },
        computed: {
            getAddr() {
                return function(i) {
                    return this.addressCarInfoMap.get(i);
                };
            }
        },
        created() {
            this.getUserMenu();
            //this.findBaseUrl();
        },
        mounted() {
            this.user = this.getLoginInfo();
            let name = window.sessionStorage.getItem('active-name');
            if (name !== undefined && name !== null && name !== '') {
                if (name === '-1') {
                    this.menuindex = name;
                } else {
                    let arr = name.split('-');
                    this.menuindex = arr[0];
                }
            }
            window.addEventListener('scroll', this.handleScroll, true);
            if (window.sessionStorage.getItem('sysConfig')) {
                this.sysConfig = JSON.parse(window.sessionStorage.getItem('sysConfig'));
                // 设置地图key
                if (this.sysConfig && this.sysConfig.map_key) {
                    window.DMap.key = this.sysConfig.map_key;
                }
                if (this.sysConfig && this.sysConfig.map_address) {
                    window.DMap.addressKey = this.sysConfig.map_address;
                }
            } else {
                // 如果缓存的配置不存在，则重新去请求一次
                // this.getSysConfig();
            }
        },
        components: {
            /*CommonMain,
            PersonInfo,*/
        },
        beforeDestroy() {
            clearInterval(this.setInterval);
        }
    };
</script>
